package com.stk.triplecity;

import android.graphics.Canvas;
import android.view.SurfaceHolder;

public class CanvasThread extends Thread {
    private SurfaceHolder _surfaceHolder;
    private Panel _panel;
    private boolean _run = false;
 
    public CanvasThread(SurfaceHolder surfaceHolder, Panel panel) {
        _surfaceHolder = surfaceHolder;
        _panel = panel;
    }
 
    public void setRunning(boolean run) {
        _run = run;
    }
 
    @Override
    public void run() {
        Canvas c;
        while (_run) {
        	c = null;
        	try {
        		if (_panel.getPaused()){
        			c = _surfaceHolder.lockCanvas(null);
    				synchronized (_surfaceHolder) {
    					_panel.onDrawPaused(c);
    				}
        		}else if (_panel.getExit()){
        			c = _surfaceHolder.lockCanvas(null);
    				synchronized (_surfaceHolder) {
    					_panel.onDrawExit(c);
    				}
        		}else{
        				c = _surfaceHolder.lockCanvas(null);
        				synchronized (_surfaceHolder) {
        					_panel.updateTiles(c);
        					_panel.onDraw(c);
        				}  
        			
        		}
        	} finally {
        		// do this in a finally so that if an exception is thrown
        		// during the above, we don't leave the Surface in an
        		// inconsistent state
        		if (c != null) {
        			_surfaceHolder.unlockCanvasAndPost(c);
        		}
        	}
        }
    }
}
